<?php

/**
 * Fait appel aux actions concernée
 *
 * @package cass
 * @author Mickaël CASTANHEIRO <mickael.castanheiro@gmail.com>
 * @version 1.0
 */

namespace cass;

class ActionController extends Singleton {

    /**
     * Constructeur de l'ActionController
     */
    protected function __construct() {}


    public function getCache(Uri $_uri) {
	$package = formatSeparatorToUpper($_uri->package, '-', false);
        $action = $_uri->action;
        $request = formatSeparatorToUpper($_uri->request, '-', true);
        $parameters = $_uri->parameters;$fileName = __PATH__ . Data::directories('actions') . $package . '/'. $action . Data::extensions('actions');
        $className = '\\action\\' . $package . '\\' . $action . 'Action';
        $methodName = 'execute' . $request;

	$fileName = __PATH__ . Data::directories('actions') . $package . '/'. $action . Data::extensions('actions');
        $className = '\\action\\' . $package . '\\' . $action . 'Action';
       
        if (file_exists($fileName)) {
            require_once $fileName;
            $objectAction = new $className;
            if (method_exists($objectAction, 'cache')) {
                $cache = $objectAction->cache();
		if ( isset($cache['execute' . $request]) ) {
		    return $cache['execute' . $request];
		}
            }
        }
        return Cache::NO;
    }

   /**
    * Exécute l'action demandée ou renvoie vers la page 404
    * @param Uri $_uri
    * @return <type>
    */
    public function execute(Uri $_uri) {
        $package = formatSeparatorToUpper($_uri->package, '-', false);
        $action = $_uri->action; 
        $request = formatSeparatorToUpper($_uri->request, '-', true);
        $parameters = $_uri->parameters;

        $fileName = __PATH__ . Data::directories('actions') . $package . '/'. $action . Data::extensions('actions');
        $className = '\\action\\' . $package . '\\' . $action . 'Action';
        $methodName = 'execute' . $request;

        if (file_exists($fileName)) {
            require_once $fileName;
            $objectAction = new $className;
            if (method_exists($objectAction, $methodName)) {
                call_user_func_array(array($objectAction, $methodName), $parameters);
                return $objectAction->getParameters();
            }
        }

        throw new error404Exception($_uri);
    }

}
